package com.zrf.gulimall.order.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author zhanrf
 * @Date 2022/1/5 0:04
 */
@EnableRabbit
@Configuration
public class OrderRabbitMqConfig {

	/** 延迟队列名字 */
	private static final String ORDER_DELAY_QUEUE_NAME = "order.delay.queue";
	/** 死信队列名字 */
	private static final String ORDER_RELEASE_QUEUE_NAME = "order.release.queue";
	/** 交换机名字 */
	private static final String ORDER_EVENT_EXCHANGE_NAME = "order-event-exchange";
	/** 死信队列路由键 */
	private static final String DEAD_LETTER_ROUTING_KEY = "order.release.order";
	/** 延迟队列路由键 */
	private static final String DELAY_ROUTING_KEY = "order.create.order";

	/**
	 * rabbitmq的序列化为json串
	 */
	@Bean
	public MessageConverter messageConverter() {
		return new Jackson2JsonMessageConverter();
	}

	@Bean
	public Queue oderDelayQueue() {
		return QueueBuilder.durable(ORDER_DELAY_QUEUE_NAME)
				.deadLetterExchange(ORDER_EVENT_EXCHANGE_NAME)
				.deadLetterRoutingKey(DEAD_LETTER_ROUTING_KEY)
				.ttl(60000).build();
	}

	@Bean
	public Queue oderReleaseQueue() {
		return QueueBuilder.durable(ORDER_RELEASE_QUEUE_NAME).build();
	}

	@Bean
	public TopicExchange orderEventExchange() {
		return ExchangeBuilder.topicExchange(ORDER_EVENT_EXCHANGE_NAME).build();
	}

	@Bean
	public Binding delayBinding() {
		return BindingBuilder.bind(oderDelayQueue()).to(orderEventExchange()).with(DELAY_ROUTING_KEY);
	}

	@Bean
	public Binding deadLetterBinding() {
		return BindingBuilder.bind(oderReleaseQueue()).to(orderEventExchange()).with(DEAD_LETTER_ROUTING_KEY);
	}

	/**
	 * 订单释放直接和库存释放进行绑定
	 */
	@Bean
	public Binding orderReleaseOtherBinding() {
		return BindingBuilder.bind(new Queue("stock.release.stock.queue")).to(new TopicExchange("order-event-exchange"))
				.with("order.release.other.#");
	}
}
